import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:shenlingwuliu_flutter/pages/mess/index.dart';
import 'package:shenlingwuliu_flutter/pages/mine/index.dart';
import 'package:shenlingwuliu_flutter/pages/task/index.dart';
import 'package:shenlingwuliu_flutter/utils/eventBus.dart';
import 'package:shenlingwuliu_flutter/utils/tokenManager.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({super.key});

  @override
  State<TabBarPage> createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 记录当前索引
  int currentIndex = 0;

  // 底部TabBar数据
  List tabBarList = [
    {
      "title": "任务",
      "default": "assets/tabs/ic_tab_btn_task.svg",
    },
    {"title": "消息", "default": "assets/tabs/ic_tab_btn_mess_nor.svg"},
    {
      "title": "我的",
      "default": "assets/tabs/ic_tab_btn_mine_nor.svg",
    }
  ];
  @override
  void initState() {
    super.initState();
    // 先获取token
    Future.delayed(Duration.zero, () async {
      await TokenManager().init();
      // ToastUtil.showInfo(TokenManager().getToken()!);
    });

    eventBus.on<LogoutEvent>().listen((event) {
      Navigator.pushNamed(context, '/login');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 中间内容
      body: SafeArea(
        child: IndexedStack(
          index: currentIndex,
          children: const [TaskPage(), MessPage(), MinePage()],
        ),
      ),
      // 底部TabBar
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        items: _barItemList(),
        currentIndex: currentIndex,
        selectedItemColor: const Color.fromARGB(255, 245, 13, 13),
        unselectedItemColor: Colors.black,
        onTap: (index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }

  // 底部导航栏组件
  List<BottomNavigationBarItem> _barItemList() {
    List<BottomNavigationBarItem> items = [];
    for (var item in tabBarList) {
      items.add(
        BottomNavigationBarItem(
            icon: SvgPicture.asset(
              item['default'],
              width: 32,
              height: 32,
            ),
            activeIcon: SvgPicture.asset(
              item['default'],
              colorFilter: const ColorFilter.mode(Colors.red, BlendMode.srcIn),
              width: 32,
              height: 32,
            ),
            label: item['title']),
      );
    }
    return items;
  }
}
